package models

import (
	"context"
	"errors"
	"go-chain-data/global"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type ScanConfig struct {
	ChainId         uint   `bson:"chainId"`
	ChainName       string `bson:"chainName"`
	RpcUrl          string `bson:"rpcUrl"`
	LastBlockNumber uint64 `bson:"lastBlockNumber"`
	Type            string `bson:"type"`
	UdunId          uint64 `bson:"udunId"`
}

func CreateScanConfig(scanConfig ScanConfig) error {
	scanClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("scan_config")
	filter := bson.D{{"rpcUrl", scanConfig.RpcUrl}, {"chainId", scanConfig.ChainId}, {"type", global.BlockChainConfig.Type}}
	result := scanClient.FindOne(context.Background(), filter)
	if err := result.Err(); errors.Is(err, mongo.ErrNoDocuments) {
		_, err = scanClient.InsertOne(context.Background(), scanConfig)
		if err != nil {
			return err
		}
		//fmt.Println("scan_config表insert成功:", one.InsertedID)
	} else {
		update := bson.M{"$set": bson.M{"lastBlockNumber": scanConfig.LastBlockNumber}}
		_, err = scanClient.UpdateOne(context.Background(), filter, update)
		if err != nil {
			return err
		}
		//fmt.Println("scan_config表update成功:", one.UpsertedID)
	}
	return nil
}
